using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 交换Buff - 交换目标与施法者的位置
/// </summary>
public class SwapBuff : BuffBase
{
    private bool m_HasSwapped;
    private Vector3 m_OriginalTargetPosition;
    private Vector3 m_OriginalCasterPosition;

    public SwapBuff(BuffData buffData, Entity caster, Entity target) : base(buffData, caster, target)
    {
    }

    protected override void OnStart()
    {
        base.OnStart();
        
        if (m_HasSwapped) return;
        
        // 保存原始位置
        m_OriginalTargetPosition = Target.transform.position;
        if (Caster != null)
        {
            m_OriginalCasterPosition = Caster.transform.position;
        }
        
        // 执行位置交换
        ExecuteSwap();
        
        // 播放交换特效
        if (BuffData.Effect != null)
        {
            var effect = GameObject.Instantiate(BuffData.Effect, Target.transform);
            effect.transform.localPosition = Vector3.zero;
        }
        
        Logger.Log($"{Target.name} ���{Caster.name} 交换了位���");
    }

    protected override void OnTick(float dt)
    {
        base.OnTick(dt);
        // 交换是瞬间效果，不需要持续处���
    }

    private void ExecuteSwap()
    {
        if (Caster == null) return;
        
        m_HasSwapped = true;
        
        // 交换位置
        Vector3 tempPosition = Target.transform.position;
        Target.transform.position = Caster.transform.position;
        Caster.transform.position = tempPosition;
        
        // 设置动画状���
        if (Target.Animator != null)
        {
            Target.Animator.SetTrigger("swapped");
        }
        
        if (Caster.Animator != null)
        {
            Caster.Animator.SetTrigger("swapped");
        }
    }

    protected override void OnFinish()
    {
        base.OnFinish();
        Logger.Log($"{Target.name} 交换效果结束");
    }

    protected override void OnRemove()
    {
        base.OnRemove();
        
        // 清理特效
        var effects = Target.GetComponentsInChildren<ParticleSystem>();
        foreach (var effect in effects)
        {
            if (effect.name.Contains("Swap"))
            {
                GameObject.Destroy(effect.gameObject);
            }
        }
    }

    public override bool IsCanMerge()
    {
        return false; // 交换效果不能叠加
    }
}
